import 'dart:convert';

import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../app_files.dart';
import 'dart:io';

Effect<FixOrderViewState> buildEffect() {
  return combineEffects(<Object, Effect<FixOrderViewState>>{
    FixOrderViewAction.onTapAddPic: _onTapAddPic,
    FixOrderViewAction.onTapPic: _onTapPic,
    FixOrderViewAction.onSubmit: _onSubmit,
    Lifecycle.initState: _initState,
  });
}

void _initState(Action action, Context<FixOrderViewState> ctx) async {
  ResultData detailRes =
      await CommonNetWork.fixOrderDetail(ctx.state.model.itemID);
  if (detailRes.success) {
    print(detailRes.data['data']);
    String jsonContent =
        CommonUtils.checkNullToString(detailRes.data['data']['bizContent']);
    String dispatchLog = CommonUtils.checkNullToString(detailRes.data['data']['bizDispatchlog']);
    if (dispatchLog.isNotEmpty) {
      ctx.state.logList = jsonDecode(dispatchLog);
    }
    ctx.state.problemContent = jsonContent;
    ctx.dispatch(FixOrderViewActionCreator.onAction());
  } else {
    CommonUtils.showErrorInfo(ctx.context, detailRes.desc);
  }
}

void _onTapAddPic(Action action, Context<FixOrderViewState> ctx) async {
  AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,
      type: 2, info: ctx.state.model);
  if (imgFile != null) {
    ctx.state.imageList.add(imgFile);
    ctx.dispatch(FixOrderViewActionCreator.onAction());
  }
}

void _onTapPic(Action action, Context<FixOrderViewState> ctx) async {
  var file = action.payload;
  int res =
      await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
  if (res == 1) {
    ctx.state.imageList.remove(file);
    ctx.dispatch(FixOrderViewActionCreator.onAction());
  } else if (res == 0) {
    await CommonUtils.showMediaAlbumView(
      ctx.context,
      initialIndex: ctx.state.imageList.indexOf(file),
      files: ctx.state.imageList,
    );
  }
}

void _onSubmit(Action action, Context<FixOrderViewState> ctx) async {
  if (ctx.state.contentController.text.length == 0) {
    CommonUtils.showErrorInfo(ctx.context, '请填写维修内容');
    return;
  }
  CommonUtils.pushRoute(ctx.context, RoutePath.fixResultView, arguments: {
    'isDetail': false,
    'repairContent': ctx.state.contentController.text,
    'repairPhotos': ctx.state.imageList,
    'model': ctx.state.model
  });
}
